//
//  JBSearchBarView.m
//  OCsinaBlog
//
//  Created by jobo on 16/4/25.
//  Copyright © 2016年 jobo. All rights reserved.
//

#import "JBSearchBarView.h"

@interface JBSearchBarView() <UITextFieldDelegate>
//文本框
@property (weak, nonatomic) IBOutlet UITextField *textField;
//取消按钮
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
//文本框右边约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textFieldRightConstrains;

//搜索图片
@property (strong, nonatomic) UIImageView *imgView ;
//箭头按钮
@property (strong,nonatomic) UIButton *arrowBtn ;

@end



@implementation JBSearchBarView

- (UIImageView *)imgView
{
    if(_imgView == nil)
    {
        UIImage *searchImg = [UIImage imageNamed:@"searchbar_textfield_search_icon"] ;
        
        UIImageView *imgView = [[UIImageView alloc] init] ;
        imgView.image = searchImg ;
        imgView.contentMode = UIViewContentModeCenter ;
        imgView.bounds = CGRectMake( 0, 0, searchImg.size.width + 15, searchImg.size.height) ;
        _imgView = imgView;
    }
    return _imgView ;
}

- (UIButton *)arrowBtn
{
    if(_arrowBtn == nil)
    {
        UIButton *arrowBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
        [arrowBtn setImage:[UIImage imageNamed:@"popover_arrow"] forState:UIControlStateNormal];
        arrowBtn.bounds = self.imgView.bounds ;
        arrowBtn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
        _arrowBtn = arrowBtn;
    }
    return _arrowBtn ;
}


+ (instancetype)searchBar
{
    return  [[[NSBundle mainBundle] loadNibNamed:@"JBSearchBarView" owner:nil options:nil] lastObject] ;
}

- (void)awakeFromNib
{
    //设置textField左边的view为图片
    
   
    self.textField.leftView = self.imgView ;
    self.textField.leftViewMode = UITextFieldViewModeAlways ;
    
    self.textField.delegate = self ;
}

//监听代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    //按钮显示
    self.cancelBtn.hidden = NO ;
    
    //文本框约束变化
    self.textFieldRightConstrains.constant = self.cancelBtn.bounds.size.width + 10;
    
    //改变leftView
    self.textField.leftView = self.arrowBtn ;
    
    
    
    return YES ; 
}

//取消按钮监听事件
- (IBAction)cancelBtnClick:(id)sender
{
    //隐藏按钮
    self.cancelBtn.hidden = YES ;
    //恢复约束
    self.textFieldRightConstrains.constant = 0 ;
    //添加约束的动画效果
    [UIView animateWithDuration:0.25 animations:^{
        [self layoutIfNeeded] ;
    }] ;
    //隐藏键盘
    [self endEditing:YES] ;
    
    self.textField.leftView = self.imgView ; 
    
}

@end
